package com.haiheng.voiceandbook.voice

import android.Manifest
import android.app.Dialog
import android.graphics.Bitmap
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.haiheng.bookmusic.base.BaseActivity
import com.haiheng.bookmusic.common.PlayBean
import com.haiheng.bookmusic.utils.*
import com.haiheng.voiceandbook.Constants
import com.haiheng.voiceandbook.R
import com.haiheng.voiceandbook.databinding.ActivityPlayerBinding
import com.haiheng.voiceandbook.helper.WeakDataHolder
import com.haiheng.voiceandbook.utils.DisplayUtil
import com.haiheng.voiceandbook.utils.SmartDialogUtils
import com.haiheng.voiceandbook.utils.ToolUtil
import com.haiheng.voiceandbook.utils.ZXingUtils
import com.tencent.bugly.crashreport.CrashReport
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest
import com.ximalaya.ting.android.opensdk.model.PlayableModel
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList
import com.ximalaya.ting.android.opensdk.model.album.Album
import com.ximalaya.ting.android.opensdk.model.live.radio.Radio
import com.ximalaya.ting.android.opensdk.model.live.schedule.Schedule
import com.ximalaya.ting.android.opensdk.model.track.Track
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener
import com.ximalaya.ting.android.opensdk.player.appnotification.NotificationColorUtils
import com.ximalaya.ting.android.opensdk.player.appnotification.XmNotificationCreater
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener
import com.ximalaya.ting.android.opensdk.player.service.NotificationChannelUtils
import com.ximalaya.ting.android.opensdk.player.service.NotificationChannelUtils.newNotificationBuilder
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException
import com.ximalaya.ting.android.opensdk.util.NetworkType
import com.ximalaya.ting.android.sdkdownloader.XmDownloadManager


/**
 * 播放器页面
 */
class PlayerActivity : BaseActivity() {


    private var mPlayerManager: XmPlayerManager? = null

    private var mUpdateProgress = true

    private var lastClickTime: Long = 0

    private val noCrashNotifation = 10000
    private var bean:PlayBean? = null

    var mUrl = "https://yidu.seaeverit.com/webview/index.html#/pages/albumPage/albumPage"
    var activityPlayerBinding: ActivityPlayerBinding? = null



    private var  startPlayTime:Long = 0 //开始播放时间
    private var  totalPlayTime:Long = 0 //总共播放时长，单位s
    private var  isStopPlay = false
    private var albumId:String = ""
    override fun initData() {

    }

    /**
     * 开启音乐
     *
     */
    fun startMusic(){
        val data = intent.getBundleExtra("bundle")
//        val bean = data?.getParcelable<PlayBean>("bean")
        bean = WeakDataHolder.getInstance().getData("bean") as PlayBean
        val album = data?.getParcelable<Album>("album")
        if (album != null) {
            albumId = album.id.toString()
        }
        mPlayerManager!!.playList(bean!!.list, bean!!.position)
        activityPlayerBinding?.tvTitle?.setText(album?.albumTitle)


        activityPlayerBinding?.ivHead?.let { GlideUtils.load(this, album!!.coverUrlLarge, it) }

        activityPlayerBinding?.tvCount?.setText(ToolUtil.getFormatNumber(album?.playCount))



    }

    override fun initView() {

        initPlayer()

    }

    override fun intiLayout() {
        activityPlayerBinding = ActivityPlayerBinding.inflate(LayoutInflater.from(this))
        setContentView(activityPlayerBinding?.getRoot())
    }

    /**
     * 初始化播放器
     */
    private fun initPlayer() {
        try {
            NotificationColorUtils.isTargerSDKVersion24More = true;
            mPlayerManager = XmPlayerManager.getInstance(this)
            mPlayerManager?.init()
            mPlayerManager?.setBreakpointResume(false)
            mPlayerManager?.addPlayerStatusListener(mPlayerStatusListener)
            mPlayerManager?.addAdsStatusListener(mAdsListener)
            mPlayerManager?.addOnConnectedListerner(object : XmPlayerManager.IConnectListener {
                override fun onConnected() {
                    mPlayerManager?.removeOnConnectedListerner(this)
                    mPlayerManager?.setPlayMode(XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE)
                    startMusic()
                }
            })

            // 此代码表示播放时会去监测下是否已经下载
            XmPlayerManager.getInstance(this).setCommonBusinessHandle(XmDownloadManager.getInstance())

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                0
            )
        }catch (ex:Exception){
            Log.e(TAG,"initPlayer:"+ex.toString())
        }


    }

    var isFinish:Boolean?=false
    override fun onDestroy() {
        super.onDestroy()
        if (mPlayerManager != null) {
            mPlayerManager!!.removePlayerStatusListener(mPlayerStatusListener)
        }

        XmPlayerManager.release()
        isFinish = true
        CommonRequest.release()
    }

    override fun onPause() {
        super.onPause()
        if (!isStopPlay){
            calculationTime(false)
        }

        reportPlay()
    }

    override fun initDataChange() {

    }

    override fun initListener() {
        //https://yidu.seaeverit.com/webview/index.html#/pages/albumPage/albumPage?id=7252091
        //收藏专辑
        activityPlayerBinding?.tvListener?.setOnClickListener {
            val data = intent.getBundleExtra("bundle")
//            val bean = WeakDataHolder.getInstance().getData("bean") as PlayBean
            val album = data?.getParcelable<Album>("album")
            var url= mUrl+"?id=${album?.id}&libraryNo="


               url = url+"${Constants.getLibraryCode()}&PhysicalAddress=${Constants.getDevicesId()}"


            showQcoreDialog(url)

        }
        //https://yidu.seaeverit.com/webview/index.html#/pages/albumPage/albumPage?album_id=37921577&track_id=300903483
        //https://yidu.seaeverit.com/webview/index.html#/pages/albumPage/albumPage?album_id=43955109&track_id=375572491
        //收藏歌单
        activityPlayerBinding?.ivLike?.setOnClickListener {

            val data = intent.getBundleExtra("bundle")
//            val bean = WeakDataHolder.getInstance().getData("bean") as PlayBean
            val album = data?.getParcelable<Album>("album")
            if (bean != null){
                var url= mUrl+"?album_id=${album?.id}&track_id=${bean?.list?.get(bean!!.position)?.dataId}&libraryNo="
                url = url+"${Constants.getLibraryCode()}&PhysicalAddress=${Constants.getDevicesId()}"
                showQcoreDialog(url)
            }



        }
        activityPlayerBinding?.ivBack?.setOnClickListener {
            finish()
        }
        activityPlayerBinding?.seekBar?.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                mPlayerManager!!.seekToByPercent(seekBar.progress / seekBar.max.toFloat())
                mUpdateProgress = true
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                mUpdateProgress = false
            }

            override fun onProgressChanged(
                seekBar: SeekBar,
                progress: Int,
                fromUser: Boolean
            ) {
            }
        })

        activityPlayerBinding?.preSound?.setOnClickListener(View.OnClickListener { mPlayerManager!!.playPre() })

        activityPlayerBinding?.playOrPause?.setOnClickListener(View.OnClickListener {
            println("MainFragmentActivity.onClick   " + mPlayerManager!!.isPlaying)
            if (mPlayerManager!!.isPlaying) {
                mPlayerManager!!.pause()
            } else {
                mPlayerManager!!.play()
            }
        })

        activityPlayerBinding?.nextSound?.setOnClickListener(View.OnClickListener {
            lastClickTime = System.currentTimeMillis()
            mPlayerManager!!.playNext()
        })
    }


    private val mPlayerStatusListener: IXmPlayerStatusListener = object : IXmPlayerStatusListener {
        override fun onSoundPrepared() {
            Log.e(
                TAG,
                "onSoundPrepared"
            )
            activityPlayerBinding?.seekBar?.setEnabled(true)
            activityPlayerBinding?.bufferingProgress?.setVisibility(View.GONE)
        }



        private fun updateButtonStatus() {
            if (mPlayerManager!!.hasPreSound()) {
                activityPlayerBinding?.preSound?.setEnabled(true)
            } else {
                activityPlayerBinding?.preSound?.setEnabled(false)
            }
            if (mPlayerManager!!.hasNextSound()) {
                activityPlayerBinding?.nextSound?.setEnabled(true)
            } else {
                activityPlayerBinding?.nextSound?.setEnabled(false)
            }
        }

        override fun onPlayStop() {
            Log.e(
                TAG,
                "onPlayStop"
            )
            calculationTime(false)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_play_normal)
        }

        override fun onPlayStart() {
            Log.e(
                TAG,
                "onPlayStart"
            )
            calculationTime(true)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_pause_normal)
        }

        /**
         * lastModel 上一首model,可能为空
         * curModel 下一首model
         */
        override fun onSoundSwitch(lastModel: PlayableModel?, curModel: PlayableModel?) {
            val model = mPlayerManager!!.currSound
            if (model != null) {
                var title: String? = null
                var coverUrl: String? = null
                var userName: String? = null
                if (model is Track) {
                    val info =
                        model
                    title = info.trackTitle
                    coverUrl = info.coverUrlLarge
                    userName = info.announcer.nickname
                } else if (model is Schedule) {
                    val program = model
                    title = program.relatedProgram.programName

                    coverUrl = program.relatedProgram.backPicUrl
                } else if (model is Radio) {
                    val radio =
                        model
                    title = radio.radioName
                    coverUrl = radio.coverUrlLarge
                }
                activityPlayerBinding?.message?.setText(title)
                activityPlayerBinding?.user?.setText(userName)
                GlideUtils.load(this@PlayerActivity, coverUrl!!,
                    activityPlayerBinding?.soundCover!!
                )
            }
            updateButtonStatus()

        }

        override fun onPlayProgress(currPos: Int, duration: Int) {
            var title: String? = ""
            val info = mPlayerManager!!.currSound
            if (info != null) {
                if (info is Track) {
                    title =
                        info.trackTitle
                } else if (info is Schedule) {
                    title = info.relatedProgram.programName
                } else if (info is Radio) {
                    title =
                        info.radioName
                }
            }
            activityPlayerBinding?.message?.setText(title)


            activityPlayerBinding?.currentTime?.setText(
                "${ToolUtil.formatTime(currPos.toLong()).toString()}"
            )

            activityPlayerBinding?.time?.setText(
                "${ToolUtil.formatTime(
                    duration.toLong()
                ).toString()}"
            )


            if (mUpdateProgress && duration != 0) {
                activityPlayerBinding?.seekBar?.setProgress((100 * currPos / duration.toFloat()).toInt())
                activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_pause_normal)

            }
            if (info is Track) {
                println("MainFragmentActivity.onPlayProgress  " + currPos + "   " + duration + "   " + info.duration)
            }
        }

        override fun onPlayPause() {
            Log.e(
                TAG,
                "onPlayPause"
            )
            calculationTime(false)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_play_normal)
        }

        override fun onSoundPlayComplete() {
            Log.e(
                TAG,
                "onSoundPlayComplete 播放完成"
            )
            calculationTime(false)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_play_normal)
        }

        override fun onError(exception: XmPlayerException): Boolean {
            Log.e(
                TAG,
                "XmPlayerException = onError " + exception.message + "   " + XmPlayerManager.getInstance(
                    this@PlayerActivity
                ).isPlaying
            )
            Log.e(
                TAG,
                ".onError   $exception"
            )
            calculationTime(false)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_play_normal)
            if (!NetworkType.isConnectTONetWork(this@PlayerActivity)) {
                Toast.makeText(this@PlayerActivity, "没有网络导致停止播放", Toast.LENGTH_SHORT).show()
            }
            return false
        }

        override fun onBufferProgress(position: Int) {
            Log.e(
                TAG,
                ".onBufferProgress onBufferProgress   $position"
            )


        }

        override fun onBufferingStart() {
            Log.e(
                TAG,
                "onBufferingStart   " + XmPlayerManager.getInstance(this@PlayerActivity)
                    .isPlaying
            )
            activityPlayerBinding?.seekBar?.setEnabled(false)
            activityPlayerBinding?.bufferingProgress?.setVisibility(View.VISIBLE)
        }

        override fun onBufferingStop() {
            Log.e(
                TAG,
                "onBufferingStop"
            )
            activityPlayerBinding?.seekBar?.setEnabled(true)
            activityPlayerBinding?.bufferingProgress?.setVisibility(View.GONE)
        }
    }

    private val mAdsListener: IXmAdsStatusListener = object : IXmAdsStatusListener {
        override fun onStartPlayAds(ad: Advertis, position: Int) {
            Log.e(
                TAG,
                "onStartPlayAds, Ad:" + ad.name + ", pos:" + position
            )
            activityPlayerBinding?.playOrPause?.setEnabled(true)
            activityPlayerBinding?.playOrPause?.setImageResource(R.mipmap.widget_pause_normal)
        }

        override fun onStartGetAdsInfo() {
            Log.e(
                TAG,
                "onStartGetAdsInfo"
            )
            activityPlayerBinding?.playOrPause?.setEnabled(false)
            activityPlayerBinding?.seekBar?.setEnabled(false)
        }

        override fun onGetAdsInfo(ads: AdvertisList) {}
        override fun onError(what: Int, extra: Int) {
            Log.e(
                TAG,
                "onError what:$what, extra:$extra"
            )
        }

        override fun onCompletePlayAds() {
            Log.e(
                TAG,
                "onCompletePlayAds"
            )
            activityPlayerBinding?.playOrPause?.setEnabled(true)
            activityPlayerBinding?.seekBar?.setEnabled(true)
            val model = mPlayerManager!!.currSound
            if (model != null && model is Track) {
                if(!isFinish!!){
                    GlideUtils.load(this@PlayerActivity, model.coverUrlLarge!!,
                        activityPlayerBinding?.soundCover!!
                    )
                }


            }
        }

        override fun onAdsStopBuffering() {
            Log.e(
                TAG,
                "onAdsStopBuffering"
            )
        }

        override fun onAdsStartBuffering() {
            Log.e(
                TAG,
                "onAdsStartBuffering"
            )
        }
    }

    /**
     * 展示二维码
     */
    private fun showQcoreDialog(url:String) {
        val dialog: Dialog = SmartDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_q_code)
        val iv_q_code = dialog.findViewById<ImageView>(R.id.iv_q_code) as ImageView
        val tvOk = dialog.findViewById<View>(R.id.tv_ok) as TextView

        Log.e(TAG, "url: $url")
        val bitmap: Bitmap = ZXingUtils.createQRImage(
            url,
            DisplayUtil.dip2px(this, 131f),
            DisplayUtil.dip2px(this, 131f)
        )
        iv_q_code.setImageBitmap(bitmap)

        val tvTitle = dialog.findViewById<View>(R.id.tv_title) as TextView

        tvTitle.setText("打开微信扫一扫即可收听")

        tvOk.setOnClickListener {
            dialog.dismiss()

        }
        dialog.show()
    }


    fun calculationTime(isStartPlay: Boolean){
        if (isStartPlay){
            isStopPlay = false
            startPlayTime = System.currentTimeMillis()
        }else{
            isStopPlay = true
            if (startPlayTime > 0){
                var playTime = (System.currentTimeMillis() - startPlayTime)/1000
                Log.e(TAG,"hwz paltTime:${playTime}")
                totalPlayTime = totalPlayTime + playTime
                Log.e(TAG,"hwz totalPlayTime:${totalPlayTime}")
                startPlayTime = System.currentTimeMillis()
            }
        }

    }

    fun reportPlay(){
        bookViewModel?.reportPlay(albumId,totalPlayTime)
    }
}
